﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GiaiquyetthutuchanhchinhEdit.ascx.cs" company="VDC-IT" author="Longlc">
//   GiaiquyetthutuchanhchinhEdit code behind
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System.Web.Security;
using VDC.COMMON.NonPersistents;
using VDC.VONE.BLL.ViewModel;
using VDC.VONE.WEB.SendSMS;

namespace VDC.VONE.WEB.Modules.HoSo.Controls
{
    #region

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Transactions;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using AdCom.Utility;

    using Geekees.Common.Controls;

    using VDC.COMMON;
    using VDC.COMMON.ExceptionHelpers;
    using VDC.VONE.BLL;
    using VDC.VONE.ENTITIES;

    #endregion

    /// <summary>
    ///     The giaiquyetthutuchanhchinh edit.
    /// </summary>
    public partial class GiaiquyetthutuchanhchinhEdit : UserControl
    {
        #region Constants

        /// <summary>
        ///     The attachment filename.
        /// </summary>
        private const string AttachmentFilename = "attachment; filename=";

        /// <summary>
        ///     The chuyen key.
        /// </summary>
        private const string ChuyenKey = "chuyen";

        /// <summary>
        ///     The close
        /// </summary>
        private const string Close = ");";

        /// <summary>
        ///     The comment key.
        /// </summary>
        private const string CommentKey = "ykien";

        /// <summary>
        ///     The content disposition.
        /// </summary>
        private const string ContentDisposition = "Content-Disposition";

        /// <summary>
        ///     The currency format.
        /// </summary>
        private const string CurrencyFormat = "#,#";

        /// <summary>
        ///     The dashes.
        /// </summary>
        private const string Dashes = "-";

        /// <summary>
        ///     The hoanthanh.
        /// </summary>
        private const string Hoanthanh = "HOANTHANH";

        /// <summary>
        ///     The dangxuly.
        /// </summary>
        private const string Dangxuly = "DANGXULY";

        /// <summary>
        ///     The default aspx
        /// </summary>
        private const string DefaultAspx = "~/default.aspx";

        /// <summary>
        ///     The document key.
        /// </summary>
        private const string DocumentKey = "tailieu";

        /// <summary>
        ///     The file upload path hoso.
        /// </summary>
        private const string FileUploadPathHoso = "FileUploadPathHoSo";

        /// <summary>
        ///     The first key format.
        /// </summary>
        private const string FirstKeyFormat = "&{0}=";

        /// <summary>
        ///     The first value format.
        /// </summary>
        private const string FirstValueFormat = "{0}&";

        /// <summary>
        ///     The level id.
        /// </summary>
        private const string LevelId = "LevelId";

        /// <summary>
        ///     The splash
        /// </summary>
        private const string Splash = @"://";

        /// <summary>
        ///     The separator.
        /// </summary>
        private const string Separator = ",";

        /// <summary>
        ///     The ma ho so one.
        /// </summary>
        private const string MaHoSoOne = "MHS1";

        /// <summary>
        ///     The main process
        /// </summary>
        private const string MainProcess = "Xử lý chính";

        /// <summary>
        ///     The mhs.
        /// </summary>
        private const string Mhs = "MHS";

        /// <summary>
        ///     The name text column.
        /// </summary>
        private const string NameTextColumn = "Name";

        /// <summary>
        ///     The no fee.
        /// </summary>
        private const string NoFee = "Không thu";

        /// <summary>
        ///     The not access
        /// </summary>
        private const string NotAccess = "Not Access";

        /// <summary>
        ///     The number format.
        /// </summary>
        private const string NumberFormat = "N";

        /// <summary>
        ///     The number pattern.
        /// </summary>
        private const string NumberPattern = @"\D+";

        /// <summary>
        ///     The one value.
        /// </summary>
        private const string OneValue = "1";

        /// <summary>
        ///     The parent.
        /// </summary>
        private new const string Parent = "Parent";

        /// <summary>
        ///     The profile status view state key.
        /// </summary>
        private const string ProfileStatusViewStateKey = "ProfileStatus";

        /// <summary>
        ///     The profile type id.
        /// </summary>
        private const string ProfileTypeId = "ProfileTypeId";

        /// <summary>
        ///     The progress key.
        /// </summary>
        private const string ProgressKey = "quatrinh";

        /// <summary>
        ///     The query string format.
        /// </summary>
        private const string QueryStringFormat = "&{0}={1}";

        /// <summary>
        ///     The quot
        /// </summary>
        private const string Quot = "\"";

        /// <summary>
        ///     The root path.
        /// </summary>
        private const string RootPath = "~";

        /// <summary>
        ///     The select profile type.
        /// </summary>
        private const string SelectProfileType = "---Chọn thủ tục---";

        /// <summary>
        ///     The separator character
        /// </summary>
        private const char SeparatorChar = '_';

        /// <summary>
        ///     The show new page five.
        /// </summary>
        private const string ShowNewPageFive = "ShowNewPage(5, ";

        /// <summary>
        ///     The show new page four.
        /// </summary>
        private const string ShowNewPageFour = "ShowNewPage(4, ";

        /// <summary>
        ///     The show new page six.
        /// </summary>
        private const string ShowNewPageSix = "ShowNewPage(6, ";

        /// <summary>
        ///     The show new page six.
        /// </summary>
        private const string ShowNewPageSeven = "ShowNewPage(7, ";

        /// <summary>
        ///     The show new page three.
        /// </summary>
        private const string ShowNewPageThree = "ShowNewPage(3, ";

        /// <summary>
        ///     The show new page two.
        /// </summary>
        private const string ShowNewPageTwo = "ShowNewPage(2, ";

        /// <summary>
        ///     The shown new page one.
        /// </summary>
        private const string ShownNewPageOne = "ShowNewPage(1, ";

        /// <summary>
        ///     The storage location profile list id.
        /// </summary>
        private const string StorageLocationProfileListId = "StorageLocationProfileListId";

        /// <summary>
        ///     The table name.
        /// </summary>
        private const string TableName = "storage";

        /// <summary>
        ///     The tien do key.
        /// </summary>
        private const string TienDoKey = "tiendo";

        /// <summary>
        /// The profile type key
        /// </summary>
        private const string ProfileTypeKey = "loaihoso";

        /// <summary>
        ///     The two value.
        /// </summary>
        private const string TwoValue = "2";

        /// <summary>
        ///     The underline.
        /// </summary>
        private const string Underline = "_";

        /// <summary>
        ///     The value format.
        /// </summary>
        private const string ValueFormat = "{0}?";

        /// <summary>
        ///     The vi vn culture.
        /// </summary>
        private const string ViVnCulture = "vi-VN";

        /// <summary>
        ///     The work key.
        /// </summary>
        private const string WorkKey = "congviec";

        /// <summary>
        ///     The zero value.
        /// </summary>
        private const string ZeroValue = "0";

        /// <summary>
        ///     The zero value.
        /// </summary>
        private const string Added = "AddedProfile";

        /// <summary>
        ///     The giaiquyetthutuchanhchinhedit aspx
        /// </summary>
        private const string GiaiquyetthutuchanhchinheditAspx = @"/Modules/HoSo/GiaiquyetthutuchanhchinhEdit.aspx";

        /// <summary>
        ///     Ho so goc session key.
        /// </summary>
        private const string HoSoGocSessionKey = "HoSoGoc";

        #endregion

        #region Fields

        /// <summary>
        ///     The profile id.
        /// </summary>
        private int profileId = HtmlHelper.GetIntFromRequestString("ProfileId", -1);

        /// <summary>
        ///     The user id.
        /// </summary>
        private int userId = -1;

        ////Task VONE_Maintain_24 add begin by longlc
        /// <summary>
        ///     The inphieu aspx type pnkh profileid.
        /// </summary>
        private const string InphieuAspxTypePnkhProfileid = "/Modules/HoSo/InPhieu.aspx?Type=PNKH&ProfileId=";

        /// <summary>
        ///     The javascript window open.
        /// </summary>
        private const string JavascriptWindowOpen = "JavaScript:window.open('";

        /// <summary>
        ///     The custompopup.
        /// </summary>
        private const string Custompopup = "', 'CustomPopUp', ";

        /// <summary>
        ///     The width height menubar no resizable yes.
        /// </summary>
        private const string WidthHeightMenubarNoResizableYes =
            "'width=900, height=768, menubar=no,location=no,resizable=yes,scrollbars=yes,status=no');";

        /// <summary>
        ///     The inphieu aspx type pbg profileid.
        /// </summary>
        private const string InphieuAspxTypePbgProfileid = "/Modules/HoSo/InPhieu.aspx?Type=PBG&ProfileId=";

        /// <summary>
        ///     The open key.
        /// </summary>
        private const string OpenKey = "open";

        ////Task VONE_Maintain_24 add end by longlc

        /// <summary>
        /// The tien do text
        /// </summary>
        private const string TienDoText = "Tiến độ";

        /// <summary>
        /// The tai lieu text
        /// </summary>
        private const string TaiLieuText = "Tài liệu";

        /// <summary>
        /// The y kien text
        /// </summary>
        private const string YKienText = "Ý kiến";

        /// <summary>
        /// The cong viec text
        /// </summary>
        private const string CongViecText = "Công việc";

        /// <summary>
        /// The qua trinh text
        /// </summary>
        private const string QuaTrinhText = "Quá trình";

        /// <summary>
        /// The chuyen xu ly text
        /// </summary>
        private const string ChuyenXuLyText = "Chuyển xử lý";

        /// <summary>
        /// The colon
        /// </summary>
        private const string Colon = @",'";

        /// <summary>
        /// The quots
        /// </summary>
        private const string Quots = @"'";

        /// <summary>
        ///     The aspnetsqlmembershipprovider.
        /// </summary>
        private const string Aspnetsqlmembershipprovider = "AspNetSqlMembershipProvider";

        /// <summary>
        /// The select profile type text
        /// </summary>
        private const string SelectProfileTypeText = "CHỌN THỦ TỤC";

        #endregion

        #region Public Properties

        /// <summary>
        ///     Gets the profile id.
        /// </summary>
        /// <value>
        ///     The profile id.
        /// </value>
        public int ProfileId
        {
            get
            {
                if (this.Session[Constants.SessionKey.ProfileId] != null)
                {
                    this.profileId = Convert.ToInt32(this.Session[Constants.SessionKey.ProfileId]);
                    this.Session[Constants.SessionKey.ProfileId] = null;
                }

                return this.profileId;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        ///     Gets The url back.
        /// </summary>
        private string UrlBack
        {
            get
            {
                string url = string.Empty;
                string firstKey = string.Empty;
                string valueKey = string.Empty;
                firstKey = this.Request.QueryString.AllKeys.Length > 0
                               ? this.Request.QueryString.AllKeys[0]
                               : string.Empty;
                valueKey = this.Request.QueryString.AllKeys.Length > 0 ? this.Request.QueryString[0] : string.Empty;
                foreach (var key in this.Request.QueryString.AllKeys)
                {
                    url += string.Format(QueryStringFormat, key, this.Request.QueryString[key]);
                }

                url = url.Replace(string.Format(FirstKeyFormat, firstKey), string.Empty);
                url = url.Replace(string.Format(FirstValueFormat, valueKey), string.Format(ValueFormat, valueKey));

                return url;
            }
        }

        #endregion

        #region Web Methods

        /// <summary>
        /// Gets the automatic date.
        /// </summary>
        /// <param name="from">From.</param>
        /// <returns>return string</returns>
        [WebMethod]
        public string GetToDate(string from)
        {
            int days = Convert.ToInt32(this.lblResolveDays.Text);

            DateTime temp = DateTime.Now.AddDays(days);
            int result = PublicFuncs.GetHolidaysBetween(DateTime.Now, temp);
            DateTime temp2 = temp.AddDays(result);

            int extraResult = PublicFuncs.GetHolidaysBetween(temp, temp2);

            DateTime final = temp2.AddDays(extraResult);

            int finalDays = PublicFuncs.GetHolidaysBetween(DateTime.Now, final);

            this.txtAppointmentDate.Text = temp.AddDays(finalDays).ToString(Constants.DateTimeDisplay);
            ////this.txtSettlementDate.Text = this.txtAppointmentDate.Text;

            return string.Empty;
        }

        #endregion

        #region Methods

        /// <summary>
        /// The btn ghilai_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void BtnGhilaiClick(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType + Constants.Dot
                                + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (this.Page.IsValid)
                {
                    if (!this.Validate())
                    {
                        return;
                    }

                    ProfileEN profile = new ProfileEN();
                    ProfileCompositionProfileListEN profileCompositionProfile = new ProfileCompositionProfileListEN();
                    WorkflowProfileEN workflowProfile = new WorkflowProfileEN();
                    ProfileService profileService = new ProfileService();
                    ProfileCompositionProfileListService profileCompositionProfileListService =
                        new ProfileCompositionProfileListService();
                    WorkflowProfileService workflowProfileService = new WorkflowProfileService();
                    ProfileStatusService profileStatusService = new ProfileStatusService();
                    NodeWorkflowService nodeWorkflowService = new NodeWorkflowService();

                    if (this.profileId != -1)
                    {
                        profile = profileService.GetProfileById(this.profileId);
                    }

                    if (this.FillDataIntoProfile(profile, profileStatusService))
                    {
                        using (TransactionScope scope = new TransactionScope())
                        {
                            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
                            {
                                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);
                                profile.Code = profileService.GetProfileById(this.profileId).Code;
                            }

                            if (this.profileId == -1)
                            {
                                this.NewProfileAction(
                                    profile,
                                    profileService,
                                    profileCompositionProfile,
                                    profileCompositionProfileListService,
                                    workflowProfile,
                                    nodeWorkflowService,
                                    workflowProfileService);
                            }
                            else
                            {
                                this.UpdateProfileAction(
                                    profile,
                                    profileService,
                                    profileCompositionProfile,
                                    profileCompositionProfileListService,
                                    workflowProfile,
                                    nodeWorkflowService,
                                    workflowProfileService);
                            }

                            ////Task VONE_Maintain_21 add begin by longlc
                            IList<NodeWorkflowEN> list = nodeWorkflowService.GetNodeWorkflowByWorkflow_Node( workflowProfile.WorkflowId, workflowProfile.NodeId);
                            ////Task VONE_Maintain_21 add end by longlc

                            if (profile.ProfileStatus.Code == Constants.ProfileStatus.TIEPNHAN)
                            {
                                this.EnableControls(false);
                                this.ddlProfileType.Enabled = true;

                                if (profile.Attachments != string.Empty)
                                {
                                    this.imgDelete.Visible = true;
                                }

                                profile = profileService.GetProfileById(this.profileId);
                                var nodeWfProfileTypeProgressService = new NodeWFProfileTypeProgressService();

                                var nodeWorkflowRollService = new NodeWorkflowRollService();

                                if (list.Count > 0)
                                {
                                    var lst = nodeWorkflowRollService.GetNodeWorkflowRollByNodeWorkflow_ToCc(list[0].NodeWorkflowId, true,
                                                                                   profile.ProfileTypeId);
                                    if (lst.Count > 0)
                                    {
                                        NodeWorkflowEN nodeWorkflow = list[0];

                                        if (nodeWorkflow != null)
                                        {
                                            var wp = new WorkflowProfileEN();
                                            var profileApprove = new ProfileApproveEN();
                                            var progressWorkService = new ProgressWorkService();

                                            var currentProfileTypeProgressId = this.GetCurrentProfileTypeProgressId(
                                                nodeWorkflow, nodeWfProfileTypeProgressService, profile);

                                            var nextProfileTypeProgressId = this.GetNextProfileTypeProgressId(
                                                nodeWorkflow, nodeWfProfileTypeProgressService, profile);

                                            IList<CoordinationEN> coordinations = new List<CoordinationEN>();

                                            this.InsertDBTransaction(
                                                    nodeWorkflow,
                                                    profile,
                                                    workflowProfileService,
                                                    profileService,
                                                    currentProfileTypeProgressId,
                                                    nextProfileTypeProgressId,
                                                    progressWorkService,
                                                    wp,
                                                    coordinations,
                                                    profileApprove);

                                            ////Gứi mail, sms cho công dân đăng ký trong hồ sơ
                                            if (nodeWorkflow.Send == "EMAIL_SMS" || nodeWorkflow.Send == "EMAIL")
                                            {
                                                this.EmailCongDan(profile);
                                            }
                                            else if (nodeWorkflow.Send == "EMAIL_SMS" || nodeWorkflow.Send == "SMS")
                                            {
                                                this.SmsCongDan(profile);
                                            }

                                            ////Gửi mail/Sms cho người nhận
                                            this.EmailSmsNguoiNhan(profile, workflowProfile, profileApprove,
                                                                   coordinations, nodeWorkflow);
                                        }

                                    }
                                    else
                                    {
                                        this.lbtChuyenxuly.Enabled = false;
                                        this.btnChuyenXuLy.Enabled = false;
                                        this.lblMessage.ForeColor = Color.Red;
                                        this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_BtnGhilaiClick_NoToDefault;
                                    }
                                }
                                ////Task VONE_Maintain_21 add end by longlc
                            }
                            else
                            {
                                this.lblMessage.ForeColor = Color.Red;
                                this.lblMessage.Text = Resource.ChuyenXuLy_BtnGuiClick_ProfileTypeInvalid;
                            }

                            if (list.Count > 0)
                            {
                                if (list[0].PrintReceipt)
                                {
                                    this.btnInPhieuTiepNhan.Visible = true;
                                }

                                if (list[0].PrintVotehandover)
                                {
                                    this.btnInPhieuBanGiao.Visible = true;
                                }
                            }

                            scope.Complete();
                        }

                        this.lbtTailieu.Enabled = true;
                        this.lbtTiendo.Enabled = true;
                        this.lbtYkien.Enabled = true;
                        this.lbtCongviec.Enabled = true;
                        this.lbtXemdon.Enabled = true;
                        this.lbtQuatrinh.Enabled = true;
                    }
                }

                LogHelper.Instance.WriteLog(HttpContext.Current.User.Identity.Name, methodName, false);
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Emails the SMS nguoi nhan.
        /// </summary>
        private void EmailSmsNguoiNhan(ProfileEN profile,
            WorkflowProfileEN wp,
            ProfileApproveEN profileApprove,
            IList<CoordinationEN> coordinations,
            NodeWorkflowEN nodeWorkflow)
        {
            EmailSmsTemplateEN emailSmsTemplate;
            EmailSmsTemplateService emailSmsTemplateService = new EmailSmsTemplateService();
            string bodyNguoiNhan = string.Empty;
            string link = this.Request.Url.Scheme + Splash + this.Request.Url.Authority
                          + GiaiquyetthutuchanhchinheditAspx + this.Request.Url.Query;

            emailSmsTemplate = emailSmsTemplateService.GetEmailSmsTemplateGetByCode(Constants.Emailsmstemp.Tthc);
            if (wp.MainUser != null && wp.SendUser != null)
            {
                if (profile.ReceivingDate != null)
                {
                    if (profile.AppointmentDate != null)
                    {
                        bodyNguoiNhan = PublicFuncs.GetFormattedTempalteEmail(
                            Constants.Emailsmstemp.Tthc,
                            emailSmsTemplate.Email,
                            nguoiNhan: wp.MainUser.FullName,
                            nguoiGui: wp.SendUser.FullName,
                            maHoSo: profile.Code,
                            tenHoSo: profile.Name,
                            loaiHoSo: profile.ProfileType.Name,
                            trangThai: profile.ProfileStatus.Name,
                            ngayTiepNhan: profile.ReceivingDate.Value.ToString(Constants.DateTimeDisplay),
                            ngayHenTra: profile.AppointmentDate.Value.ToString(Constants.DateTimeDisplay),
                            vaiTro: wp.Role,
                            lyDo: profileApprove.Reason.Replace("\n", "<br/>"),
                            link: link);
                    }
                }

                if (wp.MainUser.Send == Constants.EmailSmsConfig.Sms
                    || wp.MainUser.Send == Constants.EmailSmsConfig.EmailSms)
                {
                    string bodySms = PublicFuncs.GetFormattedTempalteSms(
                        Constants.Emailsmstemp.Tthc,
                        emailSmsTemplate.Sms,
                        nguoiGui: wp.SendUser.FullName,
                        maHoSo: profile.Code,
                        trangThai: PublicFuncs.ConvertStringToUnsign(profile.ProfileStatus.Name),
                        link: link);

                    this.SendSms(bodySms, wp.MainUser.Sms);
                }
            }

            if (bodyNguoiNhan != string.Empty)
            {
                var listAddCC = this.GetListCc(profile, nodeWorkflow, coordinations);

                string f = PublicFuncs.GetAppSettings(Constants.EmailSmsConfig.SystemMail);

                if (wp.SendUser != null && wp.SendUser.Email != string.Empty)
                {
                    f = wp.SendUser.Email;
                }

                if (wp.MainUser != null
                    && (wp.MainUser.Send == Constants.EmailSmsConfig.Email
                        || wp.MainUser.Send == Constants.EmailSmsConfig.EmailSms))
                {
                    PublicFuncs.SendMail(
                        wp.MainUser.Email,
                        f,
                        listAddCC,
                        Constants.EmailSmsConfig.ThuTucHanhChinhSubject,
                        bodyNguoiNhan,
                        this.Context);
                }
                else
                {
                    if (!string.IsNullOrEmpty(listAddCC))
                    {
                        PublicFuncs.SendMail(
                            PublicFuncs.GetAppSettings(Constants.EmailSmsConfig.SystemMail),
                            f,
                            listAddCC,
                            Constants.EmailSmsConfig.ThuTucHanhChinhSubject,
                            bodyNguoiNhan,
                            this.Context);
                    }
                }
            }
        }

        /// <summary>
        /// The get list cc.
        /// </summary>
        /// <param name="coordinations">
        /// The coordinations.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string GetListCc(ProfileEN profile, NodeWorkflowEN nodeWorkflow, IList<CoordinationEN> coordinations)
        {
            string listAddCC = string.Empty;
            IList<string> coordinationEmail = new List<string>();
            var nodeWorkflowRollService = new NodeWorkflowRollService();

            var userRoles = new List<UserRole>();
            var userService = new UserService();

            foreach (NodeWorkflowRollEN nodeWorkflowRoll in
                nodeWorkflowRollService.GetNodeWorkflowRollByNodeWorkflow_ToCc(nodeWorkflow.NodeWorkflowId, false, profile.ProfileTypeId))
            {
                var lst = userService.GetUserRoleByDepartmentAndRollName(nodeWorkflowRoll.DepartmentId, nodeWorkflowRoll.RoleName);
                userRoles.AddRange(lst);
            }

            IList<NguoiNhan> list = new List<NguoiNhan>();

            foreach (UserRole userRole in userRoles)
            {
                MembershipProvider membershipProvider = Membership.Providers[Aspnetsqlmembershipprovider];
                if (membershipProvider != null)
                {
                    var membershipUser = membershipProvider.GetUser(userRole.UserDepartment.User.UserName, false);
                    if (membershipUser != null)
                    {
                        if (membershipUser.IsApproved)
                        {
                            list.Add(
                                userRole.ConvertToNguoiNhan(
                                    this.SetDefaultUser(false, userRole.UserDepartment.UserId, nodeWorkflow.NodeWorkflowId, profile.ProfileTypeId), false));
                        }
                    }
                }
            }

            if (list.Count > 0)
            {
                UserDepartmentEN userDepartment = new UserDepartmentEN();
                UserDepartmentService userDepartmentService = new UserDepartmentService();

                foreach (var nn in list)
                {
                    userDepartment = userDepartmentService.GetUserDepartmentById(nn.NguoiNhanId);
                    if (userDepartment.User.Send == Constants.EmailSmsConfig.Email
                        || userDepartment.User.Send == Constants.EmailSmsConfig.EmailSms)
                    {
                        coordinationEmail.Add(userDepartment.User.Email);
                    }
                }

                listAddCC = string.Join(Separator, coordinationEmail);

            }

            return listAddCC;
        }

        /// <summary>
        /// Sets the default user.
        /// </summary>
        /// <param name="toCc">if set to <c>true</c> [to cc].</param>
        /// <param name="userId">The user id.</param>
        /// <param name="nodeWorkflowId">The node workflow id.</param>
        /// <param name="profileTypeId">The profile type id.</param>
        /// <returns>
        /// return bool
        /// </returns>
        private bool SetDefaultUser(bool toCc, int userId, int nodeWorkflowId, int profileTypeId)
        {
            int userIdDefault = -1;

            var lst = new List<UserDefaultEN>();
            var userDeault = new UserDefaultEN();
            var userDefaultService = new UserDefaultService();
            lst = userDefaultService.GetUserDefaultByNodeWorkflow_ToCc_ProfileType(nodeWorkflowId, toCc, profileTypeId);

            if (lst.Count > 0)
            {
                if (toCc)
                {
                    if (userDeault != lst[0])
                    {
                        userIdDefault = userDeault.UserId;
                    }

                    if (userId == userIdDefault)
                    {
                        return true;
                    }
                }
                else
                {
                    foreach (var userDefaultEn in lst)
                    {
                        if (userDefaultEn.UserId == userId)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// SMSs the cong dan.
        /// </summary>
        /// <param name="profile">The profile.</param>
        private void SmsCongDan(ProfileEN profile)
        {
            var emailSmsTemplateService = new EmailSmsTemplateService();

            var emailSmsTemplate = emailSmsTemplateService.GetEmailSmsTemplateGetByCode(Constants.Emailsmstemp.Tths);

            if (profile.SmsGet != string.Empty)
            {
                string bodySms = PublicFuncs.GetFormattedTempalteSms(
                    Constants.Emailsmstemp.Tths,
                    emailSmsTemplate.Sms,
                    maHoSo: profile.Code,
                    trangThai: PublicFuncs.ConvertStringToUnsign(profile.ProfileStatus.Name),
                    ngayHenTra: profile.AppointmentDate.Value.ToString(Constants.DateTimeDisplay));

                this.SendSms(bodySms, profile.SmsGet);
            }
        }

        /// <summary>
        /// Sends the SMS.
        /// </summary>
        /// <param name="bodySms">
        /// The body SMS.
        /// </param>
        /// <param name="phone">
        /// The phone.
        /// </param>
        private void SendSms(string bodySms, string phone)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType + Constants.Dot
                                + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);

            long mtseq = PublicFuncs.SMS_GetMaxMTSEQ();
            mtseq++; ////3 - 50

            string phoneNumber = PublicFuncs.GetValidMobileNumber(phone);
            if (!string.IsNullOrEmpty(phoneNumber))
            {
                if (bodySms.Length <= 160)
                {
                    var ws = new SMSAgentWSSoapClient();
                    int status = 10000;
                    try
                    {
                        LogHelper.Instance.WriteInfo("Begin call WS send SMS to " + phoneNumber);

                        status = ws.SendMT(
                            mtseq.ToString(CultureInfo.CurrentCulture),
                            Constants.EmailSmsConfig.Number169,
                            Constants.EmailSmsConfig.Number169,
                            Constants.EmailSmsConfig.Number8788,
                            phoneNumber,
                            Constants.EmailSmsConfig.CodeSms,
                            bodySms,
                            Constants.EmailSmsConfig.TypeSms,
                            string.Empty,
                            Constants.EmailSmsConfig.Number1,
                            Constants.EmailSmsConfig.Number1,
                            Constants.EmailSmsConfig.Number169,
                            DateTime.Now.ToString(Constants.LongDateTimeDisplay),
                            Constants.EmailSmsConfig.Number0,
                            Constants.EmailSmsConfig.OpId,
                            Constants.EmailSmsConfig.UserWs,
                            Constants.EmailSmsConfig.PassWs);

                        LogHelper.Instance.WriteInfo("End call WS send SMS to " + phoneNumber);
                        LogHelper.Instance.WriteInfo("Send sms Success.");
                    }
                    catch (Exception exception)
                    {
                        status = 10000;
                        LogHelper.Instance.WriteError(methodName + Constants.Colon + exception.Message);
                    }
                    finally
                    {
                        PublicFuncs.InsertDBSendSMS(
                            mtseq, phoneNumber, bodySms, Constants.EmailSmsConfig.CxlModuleSms, status);
                    }
                }
                else
                {
                    this.lblMessage.Text = Resource.NguoiDungList_SendSms_SMS_GL160;
                }
            }

            LogHelper.Instance.WriteLog(HttpContext.Current.User.Identity.Name, methodName, false);
            LogHelper.Instance.WriteInfo(Constants.End + methodName);
        }

        /// <summary>
        /// Emails the cong dan.
        /// </summary>
        /// <param name="profile">The profile.</param>
        private void EmailCongDan(ProfileEN profile)
        {
            var emailSmsTemplateService = new EmailSmsTemplateService();

            var emailSmsTemplate = emailSmsTemplateService.GetEmailSmsTemplateGetByCode(Constants.Emailsmstemp.Tths);

            string body = PublicFuncs.GetFormattedTempalteEmail(
                Constants.Emailsmstemp.Tths,
                emailSmsTemplate.Email,
                tenCongDan: profile.OrganName,
                maHoSo: profile.Code,
                tenHoSo: profile.Name,
                trangThai: profile.ProfileStatus.Name,
                ngayTiepNhan: profile.ReceivingDate.Value.ToString(Constants.DateTimeDisplay),
                ngayHenTra: profile.AppointmentDate.Value.ToString(Constants.DateTimeDisplay));

            if (profile.Email != string.Empty)
            {
                PublicFuncs.SendMail(
                    profile.Email,
                    PublicFuncs.GetAppSettings(Constants.EmailSmsConfig.SystemMail),
                    ////PublicFuncs.GetAppSettings(Constants.EmailSmsConfig.AdminMail),
                    string.Empty,
                    Constants.EmailSmsConfig.ThongTinHoSoSubject,
                    body,
                    this.Context);
            }
        }

        /// <summary>
        /// The insert db transaction.
        /// </summary>
        /// <param name="nodeWorkflow">
        /// The node workflow.
        /// </param>
        /// <param name="profile">
        /// The profile.
        /// </param>
        /// <param name="workflowProfileService">
        /// The workflow profile service.
        /// </param>
        /// <param name="profileService">
        /// The profile service.
        /// </param>
        /// <param name="currentProfileTypeProgressId">
        /// The current profile type progress id.
        /// </param>
        /// <param name="nextProfileTypeProgressId">
        /// The next profile type progress id.
        /// </param>
        /// <param name="progressWorkService">
        /// The progress work service.
        /// </param>
        /// <param name="wp">
        /// The wp.
        /// </param>
        /// <param name="coordinations">
        /// The coordinations.
        /// </param>
        /// <param name="profileApprove">
        /// The profile approve.
        /// </param>
        private void InsertDBTransaction(
            NodeWorkflowEN nodeWorkflow,
            ProfileEN profile,
            WorkflowProfileService workflowProfileService,
            ProfileService profileService,
            int currentProfileTypeProgressId,
            int nextProfileTypeProgressId,
            ProgressWorkService progressWorkService,
            WorkflowProfileEN wp,
            IList<CoordinationEN> coordinations,
            ProfileApproveEN profileApprove)
        {
            int progressWorkId;

            using (var scope = new TransactionScope())
            {
                if (currentProfileTypeProgressId != nextProfileTypeProgressId)
                {
                    progressWorkId = this.CurrentIdDiffNextId(
                        currentProfileTypeProgressId, nextProfileTypeProgressId, progressWorkService);
                }
                else
                {
                    progressWorkId =
                        workflowProfileService.GetWorkflowProfileByCurrent_Profile(true, this.profileId).ProgressWorkId;
                }

                if (nodeWorkflow.ProfileStatus.Code == Constants.ProfileStatus.KETTHUC)
                {
                    ProgressWorkEN progressW = progressWorkService.GetProgressWorkById(progressWorkId);
                    progressW.FinishDate = DateTime.Now;
                    progressW.Status = Hoanthanh;
                    progressWorkService.Update(progressW);
                }

                int workflowProfileId;

                this.UpdateFinishWorkflowProfile(workflowProfileService);

                ////Insert thông tin workflowprofile vào bảng WorkflowProfile
                var user = this.InsertNewWorkflowProfile(
                    nodeWorkflow, workflowProfileService, wp, progressWorkId, out workflowProfileId);

                ////Insert người nhận Cc vào bảng Coordination
                this.InsertCc(profile, nodeWorkflow, wp, coordinations, workflowProfileId);

                ////Update trang thai moi cho Profile
                profile.ProfileStatusId = nodeWorkflow.ProfileStatusId;
                profileService.Update(profile);

                ////Insert thông tin vào bảng ProfileApprove
                this.InsertProfileApprove(nodeWorkflow, profileApprove, user);

                scope.Complete();
            }
        }

        /// <summary>
        /// The insert profile approve.
        /// </summary>
        /// <param name="nodeWorkflow">The node workflow.</param>
        /// <param name="profileApprove">The profile approve.</param>
        /// <param name="user">The user.</param>
        private void InsertProfileApprove(NodeWorkflowEN nodeWorkflow, ProfileApproveEN profileApprove, int user)
        {
            var profileApproveService = new ProfileApproveService();
            profileApprove.ProfileId = this.profileId;

            profileApprove.UserId = user;

            profileApprove.ApproveDate = DateTime.Now;
            profileApprove.ProfileStatusId = nodeWorkflow.ProfileStatusId;
            profileApprove.DepartmentId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentDepartmentId]);

            profileApprove.ProfileStatusDisplay = nodeWorkflow.NextNode.Name;

            profileApproveService.Insert(profileApprove);
        }

        /// <summary>
        /// The insert cc.
        /// </summary>
        /// <param name="wp">
        /// The wp.
        /// </param>
        /// <param name="coordinations">
        /// The coordinations.
        /// </param>
        /// <param name="workflowProfileId">
        /// The workflow profile id.
        /// </param>
        private void InsertCc(ProfileEN profile, NodeWorkflowEN nodeWorkflow, WorkflowProfileEN wp, IList<CoordinationEN> coordinations, int workflowProfileId)
        {
            ////if (this.Session[GridccCheckedsKey] != null)
            ////{
            ////    var coordinationService = new CoordinationService();
            ////    IList<NguoiNhan> nguoiNhans = (List<NguoiNhan>)this.Session[GridccCheckedsKey];
            ////    UserDepartmentService userDepartmentService = new UserDepartmentService();

            ////    foreach (var nguoiNhan in nguoiNhans)
            ////    {
            ////        int uId = userDepartmentService.GetUserDepartmentById(nguoiNhan.NguoiNhanId).UserId;

            ////        if (uId != wp.MainUserId)
            ////        {
            ////            var coordination = new CoordinationEN();
            ////            coordination.WorkflowProfileId = workflowProfileId;
            ////            coordination.CoordinationUserId = uId;
            ////            coordination.Role = nguoiNhan.Role;
            ////            coordination.RW = nguoiNhan.Rw;

            ////            coordinationService.Insert(coordination);
            ////            coordinations.Add(coordination);
            ////        }
            ////    }
            ////}

            var nodeWorkflowRollService = new NodeWorkflowRollService();
            var userService = new UserService();
            var userRoles = new List<UserRole>();

            foreach (NodeWorkflowRollEN nodeWorkflowRoll in
                nodeWorkflowRollService.GetNodeWorkflowRollByNodeWorkflow_ToCc(nodeWorkflow.NodeWorkflowId, false, profile.ProfileTypeId))
            {
                var lst = userService.GetUserRoleByDepartmentAndRollName(nodeWorkflowRoll.DepartmentId, nodeWorkflowRoll.RoleName);
                userRoles.AddRange(lst);
            }

            IList<NguoiNhan> list = new List<NguoiNhan>();

            foreach (UserRole userRole in userRoles)
            {
                MembershipProvider membershipProvider = Membership.Providers[Aspnetsqlmembershipprovider];
                if (membershipProvider != null)
                {
                    var membershipUser = membershipProvider.GetUser(userRole.UserDepartment.User.UserName, false);
                    if (membershipUser != null)
                    {
                        if (membershipUser.IsApproved)
                        {
                            list.Add(
                                userRole.ConvertToNguoiNhan(
                                    this.SetDefaultUser(false, userRole.UserDepartment.UserId, nodeWorkflow.NodeWorkflowId, profile.ProfileTypeId), false));
                        }
                    }
                }
            }

            var coordinationService = new CoordinationService();
            var userDepartmentService = new UserDepartmentService();

            foreach (var nguoiNhan in list)
            {
                int uId = userDepartmentService.GetUserDepartmentById(nguoiNhan.NguoiNhanId).UserId;

                if (uId != wp.MainUserId)
                {
                    var coordination = new CoordinationEN();
                    coordination.WorkflowProfileId = workflowProfileId;
                    coordination.CoordinationUserId = uId;
                    coordination.Role = nguoiNhan.Role;
                    coordination.RW = nguoiNhan.Rw;

                    coordinationService.Insert(coordination);
                    coordinations.Add(coordination);
                }
            }
        }

        /// <summary>
        /// The insert new workflow profile.
        /// </summary>
        /// <param name="nodeWorkflow">
        /// The node workflow.
        /// </param>
        /// <param name="workflowProfileService">
        /// The workflow profile service.
        /// </param>
        /// <param name="wp">
        /// The wp.
        /// </param>
        /// <param name="progressWorkId">
        /// The progress work id.
        /// </param>
        /// <param name="workflowProfileId">
        /// The workflow profile id.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        private int InsertNewWorkflowProfile(
            NodeWorkflowEN nodeWorkflow,
            WorkflowProfileService workflowProfileService,
            WorkflowProfileEN wp,
            int progressWorkId,
            out int workflowProfileId)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            wp.ProfileId = this.profileId;
            wp.WorkflowId = nodeWorkflow.WorkflowId;
            wp.NodeId = nodeWorkflow.NextNodeId;

            int user = 0;
            user = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);

            wp.SendUserId = user;
            wp.SendDepartmentId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentDepartmentId]);

            var profileService = new ProfileService();
            var profile = profileService.GetProfileById(this.profileId);

            var nodeWorkflowRollService = new NodeWorkflowRollService();
            var lst = nodeWorkflowRollService.GetNodeWorkflowRollByNodeWorkflow_ToCc(nodeWorkflow.NodeWorkflowId, true,
                                                                           profile.ProfileTypeId);

            int mainUser = 0;

            foreach (NodeWFRoleDefaultEN nodeWfRoleDefault in lst[0].NodeWfRoleDefaults)
            {
                if (nodeWfRoleDefault.ProfileTypeId == profile.ProfileTypeId)
                {
                    mainUser = nodeWfRoleDefault.UserDefaults[0].UserId;
                }
            }

            wp.MainUserId = mainUser;

            wp.MainDepartmentId = lst[0].DepartmentId;

            wp.ProgressWorkId = progressWorkId;
            wp.IsCurrent = true;
            wp.StartDate = DateTime.Now;
            if (nodeWorkflow.ProfileStatus.Code == Constants.ProfileStatus.KETTHUC)
            {
                wp.EndDate = DateTime.Now;
            }
            else
            {
                wp.EndDate = null;
            }

            wp.Role = "Xử lý chính";
            wp.RW = true;

            workflowProfileId = workflowProfileService.Insert(wp);

            if (user != mainUser)
            {
                this.lbtChuyenxuly.Enabled = false;
                this.btnChuyenXuLy.Enabled = false;
            }
            else
            {
                this.lbtChuyenxuly.Enabled = true;
                this.btnChuyenXuLy.Enabled = true;
            }

            return user;
        }

        /// <summary>
        /// The update finish workflow profile.
        /// </summary>
        /// <param name="workflowProfileService">
        /// The workflow profile service.
        /// </param>
        private void UpdateFinishWorkflowProfile(WorkflowProfileService workflowProfileService)
        {
            WorkflowProfileEN workflowProfile;
            workflowProfile = workflowProfileService.GetWorkflowProfileByCurrent_Profile(true, this.profileId);
            workflowProfile.IsCurrent = false;
            workflowProfile.EndDate = DateTime.Now;
            workflowProfileService.Update(workflowProfile);
        }

        /// <summary>
        /// The current id diff next id.
        /// </summary>
        /// <param name="currentProfileTypeProgressId">
        /// The current profile type progress id.
        /// </param>
        /// <param name="nextProfileTypeProgressId">
        /// The next profile type progress id.
        /// </param>
        /// <param name="progressWorkService">
        /// The progress work service.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        private int CurrentIdDiffNextId(
            int currentProfileTypeProgressId, int nextProfileTypeProgressId, ProgressWorkService progressWorkService)
        {
            ProgressWorkEN progressWork;
            int progressWorkId;
            progressWork = progressWorkService.GetProgressWorkByProfileTypeProgress_Profile(
                currentProfileTypeProgressId, this.profileId);

            if (progressWork != null)
            {
                progressWork.FinishDate = DateTime.Now;
                progressWork.Status = Hoanthanh;
                progressWorkService.Update(progressWork);
            }

            ProgressWorkEN prow =
                progressWorkService.GetProgressWorkByProfileTypeProgress_Profile(
                    nextProfileTypeProgressId, this.profileId);

            if (prow != null)
            {
                prow.FinishDate = null;
                prow.Status = Dangxuly;
                progressWorkService.Update(prow);
                progressWorkId = prow.ProgressWorkId;
            }
            else
            {
                var progress = new ProgressWorkEN();
                progress.ProfileTypeProgressId = nextProfileTypeProgressId;
                progress.ProfileId = this.profileId;
                progress.StartDate = DateTime.Now;
                progress.Status = Dangxuly;
                progressWorkId = progressWorkService.Insert(progress);
            }

            return progressWorkId;
        }

        /// <summary>
        /// The get next profile type progress id.
        /// </summary>
        /// <param name="nodeWorkflow">
        /// The node workflow.
        /// </param>
        /// <param name="nodeWfProfileTypeProgressService">
        /// The node wf profile type progress service.
        /// </param>
        /// <param name="profile">
        /// The profile.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        private int GetNextProfileTypeProgressId(
            NodeWorkflowEN nodeWorkflow,
            NodeWFProfileTypeProgressService nodeWfProfileTypeProgressService,
            ProfileEN profile)
        {
            NodeWFProfileTypeProgressEN nodeWfProfileTypeProgress =
                nodeWfProfileTypeProgressService.GetNodeWfDefaultBy_NodeWorkflowProfileTypeId(
                    nodeWorkflow.NodeWorkflowId, profile.ProfileTypeId);

            int nextProfileTypeProgressId = 0;
            if (nodeWfProfileTypeProgress != null)
            {
                nextProfileTypeProgressId = nodeWfProfileTypeProgress.ProfileTypeProgressId;
            }

            return nextProfileTypeProgressId;
        }

        /// <summary>
        /// The btn huy_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void BtnHuyClick(object sender, EventArgs e)
        {
            this.LoadForm();
        }

        ////Task VONE_Maintain_24 add begin by longlc
        /// <summary>
        /// BTNs the in phieu.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void BtnInPhieuTiepNhan(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType + Constants.Dot
                               + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.InPhieuTiepNhanAction();

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// BTNs the in phieu ban giao.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void BtnInPhieuBanGiao(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType + Constants.Dot
                               + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.InPhieuBanGiaoAction();

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }
        ////Task VONE_Maintain_24 add end by longlc

        /// <summary>
        /// The btn quaylai_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void BtnQuaylaiClick(object sender, EventArgs e)
        {
            if (this.UrlBack != string.Empty && !PublicFuncs.IsNumber(this.UrlBack))
            {
                if (PublicFuncs.IsLocalUrl(this.UrlBack))
                {
                    this.Response.Redirect(this.UrlBack, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                }
            }
            else
            {
                this.Response.Redirect(DefaultAspx, false);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        /// <summary>
        /// The cvfile attachments_ server validate.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        protected void CvfileAttachmentsServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = this.fileAttachments.FileBytes.Length <= (10 * 1024 * 1024);
        }

        /// <summary>
        /// The cvfile fileAttachmentsOriginal_ server validate.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        protected void CvfileAttachmentsOriginalServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = this.fileAttachmentsOriginal.FileBytes.Length <= (10 * 1024 * 1024);
        }

        /// <summary>
        /// The cvfile fileAttachmentsOriginal_ server validate.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        protected void CvfileAttachmentsOriginalServerValidate2(object source, ServerValidateEventArgs args)
        {
            args.IsValid = this.fileAttachmentsOriginal.FileName.Length < (260 - 140);
        }

        /// <summary>
        /// The cvfile attachments_ server validate.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        protected void CvfileAttachmentsServerValidate2(object source, ServerValidateEventArgs args)
        {
            args.IsValid = this.fileAttachments.FileName.Length < (260 - 140);
        }

        /// <summary>
        /// The ddl profile type_ selected index changed.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void DdlProfileTypeSelectedIndexChanged(object sender, EventArgs e)
        {
            this.lstRequirement.DataSource = null;
            this.lstLegalGround.DataSource = null;
            this.lstComposition.Items.Clear();
            this.lblResultsImplementation.Text = string.Empty;

            ProfileTypeService profileTypeService = new ProfileTypeService();
            ProfileTypeEN profileType = new ProfileTypeEN();

            if (this.ddlProfileType.SelectedIndex != 0)
            {
                this.lblProfileAmount.Visible = true;
                this.lblBo.Visible = true;
                this.lblNoGT.Visible = true;
                this.lblResolveDays.Visible = true;
                this.lblDates.Visible = true;
                this.lblFees.Visible = true;

                int profileTypeId = Convert.ToInt32(this.ddlProfileType.SelectedValue);
                profileType.ProfileTypeId = profileTypeId;

                this.BindRequirement(profileType);

                this.BindLegalGroup(profileType);

                this.BindFirstComposition(profileType);

                this.BindExtra(profileTypeService, profileTypeId);

                int days = Convert.ToInt32(this.lblResolveDays.Text);

                DateTime temp = DateTime.Now.AddDays(days);
                int result = PublicFuncs.GetHolidaysBetween(DateTime.Now, temp);
                DateTime temp2 = temp.AddDays(result);

                int extraResult = PublicFuncs.GetHolidaysBetween(temp, temp2);

                DateTime final = temp2.AddDays(extraResult);

                int finalDays = PublicFuncs.GetHolidaysBetween(DateTime.Now, final);

                this.txtAppointmentDate.Text = temp.AddDays(finalDays).ToString(Constants.DateTimeDisplay);
                ////this.txtSettlementDate.Text = this.txtAppointmentDate.Text;

                this.lblMessage.Text = string.Empty;
            }
            else
            {
                this.lblProfileAmount.Visible = false;
                this.lblBo.Visible = false;
                this.lblNoGT.Visible = false;
                this.lblResolveDays.Visible = false;
                this.lblDates.Visible = false;
                this.lblFees.Visible = false;
            }
        }

        /// <summary>
        /// Handles the Click event of the imgDelete control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="ImageClickEventArgs"/> instance containing the event data.
        /// </param>
        protected void ImgDeleteClick(object sender, ImageClickEventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            if (this.profileId != -1)
            {
                ProfileService profileService = new ProfileService();
                ProfileEN profile = profileService.GetProfileById(this.profileId);
                profile.Attachments = string.Empty;
                profileService.Update(profile);
                this.lblDon.Text = string.Empty;
                this.imgDelete.Visible = false;
                this.lblMessage.ForeColor = Color.Blue;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_ImgDeleteClick_DeleteAttachmentsProfile;
            }
        }

        /// <summary>
        /// Handles the OnClick event of the BtnProfileTypeSelect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void BtnProfileTypeSelect_OnClick(object sender, EventArgs e)
        {
            var profileTypeService = new ProfileTypeService();
            if (!string.IsNullOrEmpty(this.txtProfileTypeCode.Text.Trim()))
            {
                var lst = profileTypeService.GetProfileTypeByCode(this.txtProfileTypeCode.Text.Trim());
             
                var query = (from pt in lst
                            where pt.Workflow != null && pt.Workflow.Active
                            select pt).ToList();

                switch (query.Count)
                {
                    case 1:
                        var id = query[0].ProfileTypeId;
                        for (int i = 0; i < this.ddlProfileType.Items.Count; i++)
                        {
                            if (this.ddlProfileType.Items[i].Value == id.ToString())
                            {
                                this.lblProfileType.Text = PublicFuncs.HtmlDecode(this.ddlProfileType.Items[i].Text);
                                this.ddlProfileType.SelectedIndex = i;
                                this.DdlProfileTypeSelectedIndexChanged(this.ddlProfileType, null);
                                break;
                            }
                        }
                        break;
                    default:
                        this.ShowPoupupProfileType(this.txtProfileTypeCode.Text.Trim());
                        break;
                }
            }
            else
            {
                this.ShowPoupupProfileType(this.txtProfileTypeCode.Text.Trim());
            }
        }

        /// <summary>
        /// The lbt chuyenxuly_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtChuyenxulyClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            ////var profileService = new ProfileService();
            ////var profile = profileService.GetProfileById(this.profileId);
            ////string title = profile.Name + " - " + profile.Code;

            string script = ShowNewPageFive + this.profileId + Colon + ChuyenXuLyText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), ChuyenKey, script, true);
        }

        /// <summary>
        /// The lbt congviec_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtCongviecClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            ////var profileService = new ProfileService();
            ////var profile = profileService.GetProfileById(this.profileId);
            ////string title = profile.Name + " - " + profile.Code;

            string script = ShowNewPageThree + this.profileId + Colon + CongViecText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), WorkKey, script, true);
        }

        /// <summary>
        /// The lbt quatrinh_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtQuatrinhClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            ////var profileService = new ProfileService();
            ////var profile = profileService.GetProfileById(this.profileId);
            ////string title = profile.Name + " - " + profile.Code;

            string script = ShowNewPageFour + this.profileId + Colon + QuaTrinhText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), ProgressKey, script, true);
        }

        /// <summary>
        /// The lbt tailieu_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void lbtnHoSo_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "HoSoGoc")
            {
                if (this.ViewState[Constants.SessionKey.ProfileId] != null)
                {
                    this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);
                }

                if (this.profileId != -1)
                {
                    ProfileService profileService = new ProfileService();
                    ProfileEN profile = profileService.GetProfileById(this.profileId);
                    var lst = profile.AttachmentsOriginal.Split(';');
                    var filePath = e.CommandArgument as string;
                    string fileToDownload = string.Empty;

                    if (filePath != null)
                    {
                        foreach (var s in lst)
                        {
                            if (s.Contains(filePath))
                            {
                                fileToDownload = s;
                                break;
                            }
                        }

                        string path = Path.Combine(this.Server.MapPath(RootPath), fileToDownload);
                        string fileName = Path.GetFileName(path);
                        if (File.Exists(path) && !string.IsNullOrEmpty(fileName))
                        {
                            this.Response.Clear();

                            this.Response.AppendHeader(
                                ContentDisposition, AttachmentFilename + Quot + fileName.Split(SeparatorChar)[1] + Quot);
                            this.Response.ContentType = PublicFuncs.GetContentType(fileName);

                            this.Response.WriteFile(path);

                            this.Response.Flush();
                            this.Response.End();
                        }
                        else
                        {
                            this.lblMessage.ForeColor = Color.Red;
                            this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_LbtXemdonClick_NoExistFile;
                            this.lblNotFile.Text = Resource.GiaiquyetthutuchanhchinhEdit_LbtXemdonClick_NoExistFile;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// The lbt tailieu_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtTailieuClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            ////var profileService = new ProfileService();
            ////var profile = profileService.GetProfileById(this.profileId);
            ////string title = profile.Name + " - " + profile.Code;

            string script = ShownNewPageOne + this.profileId + Colon + TaiLieuText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), DocumentKey, script, true);
        }

        /// <summary>
        /// The lbt thongtinchung_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtThongtinchungClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            ////this.ddlStorageLocation.ForceRenderInitialScript();

            ////ProfileService profileService = new ProfileService();
            ////ProfileEN profile = profileService.GetProfileById(this.profileId);
            ////this.ddlStorageLocation.SelectNode(
            ////    profile.StorageLocationProfileList.StorageLocationProfileListId.ToString());
            ////this.ddlStorageLocation.InitialDropdownText = profile.StorageLocationProfileList.Name;
            ////this.ddlStorageLocation.DropdownText = profile.StorageLocationProfileList.Name;
        }

        /// <summary>
        /// The lbt tiendo_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtTiendoClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);
            }

            ////var profileService = new ProfileService();
            ////var profile = profileService.GetProfileById(this.profileId);
            ////string title = profile.Name + " - " + profile.Code;

            string script = ShowNewPageSix + this.profileId + Colon + TienDoText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), TienDoKey, script, true);
        }

        /// <summary>
        /// The lbt xemdon_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtXemdonClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            if (this.profileId != -1)
            {
                ProfileService profileService = new ProfileService();
                ProfileEN profile = profileService.GetProfileById(this.profileId);
                string path = Path.Combine(this.Server.MapPath(RootPath), profile.Attachments);
                string fileName = Path.GetFileName(path);
                if (File.Exists(path) && !string.IsNullOrEmpty(fileName))
                {
                    this.Response.Clear();

                    this.Response.AppendHeader(
                        ContentDisposition, AttachmentFilename + Quot + fileName.Split(SeparatorChar)[1] + Quot);
                    this.Response.ContentType = PublicFuncs.GetContentType(fileName);

                    this.Response.WriteFile(path);

                    this.Response.Flush();
                    this.Response.End();
                }
                else
                {
                    this.lblMessage.ForeColor = Color.Red;
                    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_LbtXemdonClick_NoExistFile;
                    this.lblNotFile.Text = Resource.GiaiquyetthutuchanhchinhEdit_LbtXemdonClick_NoExistFile;
                }
            }
        }

        /// <summary>
        /// The lbt ykien_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtYkienClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            ////var profileService = new ProfileService();
            ////var profile = profileService.GetProfileById(this.profileId);
            ////string title = profile.Name + " - " + profile.Code;

            string script = ShowNewPageTwo + this.profileId + Colon + YKienText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), CommentKey, script, true);
        }

        /// <summary>
        /// BTNs the chuyen xu ly click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void BtnChuyenXuLyClick(object sender, EventArgs e)
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            var profileService = new ProfileService();
            var profile = profileService.GetProfileById(this.profileId);
            string title = profile.Name + " - " + profile.Code;

            string script = ShowNewPageFive + this.profileId + Colon + title + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), ChuyenKey, script, true);
        }

        /// <summary>
        /// The page_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType + Constants.Dot
                                + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.userId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);

                ////this.CalendarExtender1.StartDate = DateTime.Now;
                ////this.CalendarExtender2.StartDate = DateTime.Now;
                ////this.CalendarExtender3.StartDate = DateTime.Now;

                if (!this.Page.IsPostBack)
                {
                    this.LoadForm();
                }

                this.txtProfileTypeCode.Focus();

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// The bind composition.
        /// </summary>
        /// <param name="profile">
        /// The profile.
        /// </param>
        private void BindComposition(ProfileEN profile)
        {
            this.BindFirstComposition(profile.ProfileType);
            foreach (ListItem item in this.lstComposition.Items)
            {
                foreach (ProfileCompositionProfileListEN compositionProfile in profile.ProfileCompositionProfileLists)
                {
                    if (compositionProfile.CompositionProfileListId == int.Parse(item.Value))
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        /// <summary>
        /// The bind extra.
        /// </summary>
        /// <param name="profileTypeService">
        /// The profile type service.
        /// </param>
        /// <param name="profileTypeId">
        /// The profile type id.
        /// </param>
        private void BindExtra(ProfileTypeService profileTypeService, int profileTypeId)
        {
            ProfileTypeEN profileType = new ProfileTypeEN();
            profileType = profileTypeService.GetProfileTypeById(profileTypeId);
            if (profileType != null)
            {
                this.lblProfileAmount.Text = profileType.AmountProfile.ToString(CultureInfo.CurrentCulture);
                this.lblResolveDays.Text = profileType.ResolveDays.ToString(CultureInfo.CurrentCulture);
                CultureInfo ci = CultureInfo.CreateSpecificCulture(ViVnCulture);
                ci.NumberFormat.CurrencyDecimalDigits = 0;
                this.lblFees.Text = profileType.Fees == 0 ? NoFee : profileType.Fees.ToString(CurrencyFormat);
                if (profileType.ResultsImplementationListId != 0)
                {
                    this.lblResultsImplementation.Text = profileType.ResultsImplementationList.Name;
                }
            }
        }

        ////Task VONE_Maintain_24 add begin by longlc
        /// <summary>
        /// The in phieu tiep nhan action.
        /// </summary>
        private void InPhieuTiepNhanAction()
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);
            }

            string path = InphieuAspxTypePnkhProfileid + this.profileId;

            string popupScript = JavascriptWindowOpen + path + Custompopup + WidthHeightMenubarNoResizableYes;

            ScriptManager.RegisterStartupScript(this, this.GetType(), OpenKey, popupScript, true);
        }

        /// <summary>
        /// Ins the phieu ban giao action.
        /// </summary>
        private void InPhieuBanGiaoAction()
        {
            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);
            }

            string path = InphieuAspxTypePbgProfileid + this.profileId;

            string popupScript = JavascriptWindowOpen + path + Custompopup
                                 + WidthHeightMenubarNoResizableYes;

            ScriptManager.RegisterStartupScript(this, this.GetType(), OpenKey, popupScript, true);
        }
        ////Task VONE_Maintain_24 add end by longlc

        /// <summary>
        /// Gets the current profile type progress id.
        /// </summary>
        /// <param name="nodeWorkflow">The node workflow.</param>
        /// <param name="nodeWfProfileTypeProgressService">The node wf profile type progress service.</param>
        /// <param name="profile">The profile.</param>
        /// <returns></returns>
        private int GetCurrentProfileTypeProgressId(
            NodeWorkflowEN nodeWorkflow,
            NodeWFProfileTypeProgressService nodeWfProfileTypeProgressService,
            ProfileEN profile)
        {
            int nwId = this.DeQuy(nodeWorkflow);
            int currentProfileTypeProgressId = 0;

            if (nwId != 0)
            {
                NodeWFProfileTypeProgressEN node =
                    nodeWfProfileTypeProgressService.GetNodeWfDefaultBy_NodeWorkflowProfileTypeId(
                        nwId, profile.ProfileTypeId);
                if (node != null)
                {
                    currentProfileTypeProgressId = node.ProfileTypeProgressId;
                }
            }
            else
            {
                currentProfileTypeProgressId = 0;
            }

            return currentProfileTypeProgressId;
        }

        /// <summary>
        /// Des the quy.
        /// </summary>
        /// <param name="nodeWorkflow">
        /// The node workflow.
        /// </param>
        /// <returns>
        /// return int
        /// </returns>
        private int DeQuy(NodeWorkflowEN nodeWorkflow)
        {
            var nodeWorkflowService = new NodeWorkflowService();
            NodeWorkflowEN prev = (from node in nodeWorkflowService.GetNodeWorkflowByNextNodeId(nodeWorkflow.NodeId)
                                   where node.WorkflowId == nodeWorkflow.WorkflowId
                                   select node).FirstOrDefault();

            if (prev != null)
            {
                if (prev.Node.NodeType.Code == Constants.Nodetype.Condition)
                {
                    this.DeQuy(prev);
                }

                return prev.NodeWorkflowId;
            }

            return 0;
        }

        /// <summary>
        /// The bind first composition.
        /// </summary>
        /// <param name="profileType">
        /// The profile type.
        /// </param>
        private void BindFirstComposition(ProfileTypeEN profileType)
        {
            this.lblBo.Visible = true;
            this.lblNoGT.Visible = true;
            this.lblDates.Visible = true;
            this.lstComposition.Items.Clear();

            foreach (ProfileTypeCompositionProfileListEN profileTypeCompositionProfileList in
                profileType.ProfileTypeCompositionProfileLists.OrderBy(c => c.CompositionProfileList.Name))
            {
                this.lstComposition.Items.Add(
                    new ListItem(
                        PublicFuncs.HtmlEncode(profileTypeCompositionProfileList.CompositionProfileList.Name.Replace("\n", "<br/>")),
                        profileTypeCompositionProfileList.CompositionProfileList.CompositionProfileListId.ToString(CultureInfo.CurrentCulture)));
            }
        }

        /// <summary>
        /// The bind legal group.
        /// </summary>
        /// <param name="profileType">
        /// The profile type.
        /// </param>
        private void BindLegalGroup(ProfileTypeEN profileType)
        {
            IList<LegalGroundsListEN> legalGroundsList = new List<LegalGroundsListEN>();
            foreach (
                ProfileTypeLegalGroundsListEN profileTypeLegalGroundsList in profileType.ProfileTypeLegalGroundsLists)
            {
                LegalGroundsListEN legalGround = profileTypeLegalGroundsList.LegalGroundsList;
                legalGroundsList.Add(legalGround);
            }

            var ordered = legalGroundsList.OrderBy(r => r.Name).ToList();
            this.lstLegalGround.DataSource = ordered;
            this.lstLegalGround.DataBind();
        }

        /// <summary>
        ///     The bind level.
        /// </summary>
        private void BindLevel()
        {
            LevelService levelService = new LevelService();
            this.ddlLevel.DataSource = levelService.GetLevels();
            this.ddlLevel.DataValueField = LevelId;
            this.ddlLevel.DataTextField = NameTextColumn;
            this.ddlLevel.DataBind();
        }

        /// <summary>
        ///     The bind profile type.
        /// </summary>
        private void BindProfileType()
        {
            ProfileTypeService profileTypeService = new ProfileTypeService();
            IList<ProfileTypeEN> profileTypes = new List<ProfileTypeEN>();
            profileTypes = profileTypeService.GetProfileTypeByWorkflowActive();
            this.ddlProfileType.DataSource = profileTypes;
            this.ddlProfileType.DataTextField = NameTextColumn;
            this.ddlProfileType.DataValueField = ProfileTypeId;
            this.ddlProfileType.DataBind();
            this.ddlProfileType.Items.Insert(0, new ListItem(SelectProfileType, ZeroValue));
        }

        /// <summary>
        /// The bind requirement.
        /// </summary>
        /// <param name="profileType">
        /// The profile type.
        /// </param>
        private void BindRequirement(ProfileTypeEN profileType)
        {
            IList<RequirementsListEN> requirementsList = new List<RequirementsListEN>();
            foreach (
                ProfileTypeRequirementsListEN profileTypeRequirementsList in profileType.ProfileTypeRequirementsLists)
            {
                RequirementsListEN requirement = profileTypeRequirementsList.RequirementsList;
                requirementsList.Add(requirement);
            }

            var ordered = requirementsList.OrderBy(r => r.Name).ToList();
            this.lstRequirement.DataSource = ordered;
            this.lstRequirement.DataBind();
        }

        /// <summary>
        ///     The bind storages.
        /// </summary>
        private void BindStorages()
        {
            StorageLocationProfileListService storageLocationProfileListService =
                new StorageLocationProfileListService();
            DataTable dt = new DataTable(TableName);
            dt.Columns.Add(StorageLocationProfileListId);
            dt.Columns.Add(NameTextColumn);
            dt.Columns.Add(Parent);
            IList<StorageLocationProfileListEN> list =
                storageLocationProfileListService.GetStorageLocationProfileLists();

            foreach (StorageLocationProfileListEN storageLocation in list)
            {
                dt.Rows.Add(storageLocation.StorageLocationProfileListId, storageLocation.Name, storageLocation.Parent);
            }

            ASTreeViewDataTableColumnDescriptor descriptor = new ASTreeViewDataTableColumnDescriptor(
                NameTextColumn, StorageLocationProfileListId, Parent);
            ////this.ddlStorageLocation.DataSourceDescriptor = descriptor;
            ////this.ddlStorageLocation.DataSource = dt;
            ////this.ddlStorageLocation.DataBind();
        }

        /// <summary>
        ///     The disable all.
        /// </summary>
        private void DisableAll()
        {
            this.lstComposition.Enabled = false;
            this.txtName.Enabled = false;
            this.txtPhone.Enabled = false;
            this.txtSms.Enabled = false;
            this.txtEmail.Enabled = false;
            this.txtReceivingDate.Enabled = false;
            this.txtAppointmentDate.Enabled = false;
            this.ddlLevel.Enabled = false;
            this.ddlObject.Enabled = false;
            this.txtOrgan.Enabled = false;
            this.txtAddress.Enabled = false;
            this.CalendarExtender1.EnabledOnClient = false;
            this.CalendarExtender2.EnabledOnClient = false;
            ////this.CalendarExtender3.EnabledOnClient = false;
            ////this.ddlStorageLocation.Enabled = false;
            ////this.txtSettlementDate.Enabled = false;
            this.txtNotes.Enabled = false;
            this.fileAttachments.Enabled = false;
            this.fileAttachmentsOriginal.Enabled = false;
            this.btnGhilai.Enabled = false;
            this.btnHuy.Enabled = false;
            this.imgDelete.Visible = false;
        }

        /// <summary>
        /// Enables the controls.
        /// </summary>
        /// <param name="p">
        /// if set to <c>true</c> [p].
        /// </param>
        private void EnableControls(bool p)
        {
            this.lbtTiendo.Enabled = p;
            ////this.lbtTailieu.Enabled = p;
            this.lbtXemdon.Enabled = p;
            this.lbtYkien.Enabled = p;
            this.lbtCongviec.Enabled = p;
            this.lbtQuatrinh.Enabled = p;
            if (!p)
            {
                this.lbtChuyenxuly.Enabled = !p;
                ////Task VONE_Maintain_24 add begin by longlc
                this.btnChuyenXuLy.Enabled = !p;
                ////Task VONE_Maintain_24 add end by longlc
            }
        }

        /// <summary>
        /// Fills the data into profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="profileStatusService">The profile status service.</param>
        /// <returns></returns>
        private bool FillDataIntoProfile(ProfileEN profile, ProfileStatusService profileStatusService)
        {
            if (this.ViewState[ProfileStatusViewStateKey] != null)
            {
                profile.ProfileStatusId =
                    profileStatusService.GetProfileStatusByCode(this.ViewState[ProfileStatusViewStateKey].ToString())
                                        .ProfileStatusId;

                ////profileStatusService.GetProfileStatusByName(this.txtProfileStatus.Text.Trim()).ProfileStatusId;
            }

            profile.ProfileTypeId = Convert.ToInt32(this.ddlProfileType.SelectedValue);
            profile.LevelId = Convert.ToInt32(this.ddlLevel.SelectedValue);

            ////Task VONE_Maintain_18 delete begin by longlc
            ////ASTreeViewNode node = this.ddlStorageLocation.GetSelectedNode();
            ////if (node != null)
            ////{
            ////    profile.StorageLocationProfileListId = Convert.ToInt32(node.NodeValue);
            ////}
            ////Task VONE_Maintain_18 delete end by longlc

            ////Task VONE_Maintain_18 add begin by longlc

            var storageLocationProfileListService = new StorageLocationProfileListService();
            profile.StorageLocationProfileListId = storageLocationProfileListService.GetStorageLocationProfileLists()[0].StorageLocationProfileListId;

            ////Task VONE_Maintain_18 add end by longlc

            if (this.userId == -1)
            {
                this.userId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);
            }

            profile.CreateUserId = this.userId;

            if (this.profileId == -1)
            {
                profile.Code = this.GenerateCode().Trim();
            }

            profile.Name = this.txtName.Text.Trim();
            profile.SmsGet = this.txtSms.Text.Trim();
            profile.Email = this.txtEmail.Text.Trim();
            profile.CreateDate = DateTime.Now;

            DateTime dt1;
            if (!DateTime.TryParseExact(this.txtReceivingDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture, DateTimeStyles.None, out dt1))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_FillDataIntoProfile_TiepNhanNotValid;
                return false;
            }

            ////profile.ReceivingDate = DateTime.ParseExact(
            ////    this.txtReceivingDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture);

            profile.ReceivingDate = dt1;

            if (!DateTime.TryParseExact(this.txtAppointmentDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture, DateTimeStyles.None, out dt1))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_FillDataIntoProfile_HenTraNotValid;
                return false;
            }

            ////profile.AppointmentDate = DateTime.ParseExact(
            ////    this.txtAppointmentDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture);

            profile.AppointmentDate = dt1;

            profile.Object = this.ddlObject.SelectedValue == OneValue ? true : false;

            ////if (!DateTime.TryParseExact(this.txtSettlementDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture, DateTimeStyles.None, out dt1))
            ////{
            ////    this.lblMessage.ForeColor = Color.Red;
            ////    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_FillDataIntoProfile_HenGQNotValid;
            ////    return false;
            ////}

            ////profile.SettlementDate = DateTime.ParseExact(
            ////    this.txtSettlementDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture);

            ////profile.SettlementDate = dt1;

            profile.Notes = this.txtNotes.Text.Trim();

            //// save file server
            if (this.fileAttachments.HasFile)
            {
                string path = string.Empty;
                string fileName = string.Empty;
                fileName = Guid.NewGuid().ToString(NumberFormat) + Underline
                           + this.fileAttachments.FileName.Replace(Underline, Dashes);
                path = Path.Combine(
                    this.Server.MapPath(RootPath), PublicFuncs.GetAppSettings(FileUploadPathHoso), fileName);
                this.fileAttachments.PostedFile.SaveAs(path);
                profile.Attachments = Path.Combine(PublicFuncs.GetAppSettings(FileUploadPathHoso), fileName);
            }
            else
            {
                profile.Attachments = profile.Attachments;
            }

            profile.OrganName = this.txtOrgan.Text.Trim();
            profile.Address = this.txtAddress.Text.Trim();
            profile.Phone = this.txtPhone.Text.Trim();

            //// Task VONE_Maintain_18 add begin by longlc

            var sb = new StringBuilder();

            HttpFileCollection hfc = Request.Files;
            for (int i = 1; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    string path = string.Empty;
                    string fileName = string.Empty;
                    fileName = Guid.NewGuid().ToString(NumberFormat) + Underline
                               + hfc[i].FileName.Replace(Underline, Dashes);
                    path = Path.Combine(
                        this.Server.MapPath(RootPath), PublicFuncs.GetAppSettings(FileUploadPathHoso), fileName);
                    hpf.SaveAs(path);
                    sb.Append(Path.Combine(PublicFuncs.GetAppSettings(FileUploadPathHoso), fileName));
                    sb.Append(";");
                }
            }

            if (string.IsNullOrEmpty(profile.AttachmentsOriginal))
            {
                profile.AttachmentsOriginal = sb.ToString();
            }
            else
            {
                profile.AttachmentsOriginal += sb.ToString();
            }
            //// Task VONE_Maintain_18 add end by longlc

            ////Task VONE_Maintain_51 add begin by longlc
            if (profileId == -1)
            {
                profile.IsOpen = false;
            }
            else
            {
                profile.IsOpen = true;
            }
            ////Task VONE_Maintain_51 add end by longlc

            return true;
        }

        /// <summary>
        ///     Generates the code.
        /// </summary>
        /// <returns>return string code ho so</returns>
        private string GenerateCode()
        {
            string result = MaHoSoOne;
            ProfileService profileService = new ProfileService();
            ProfileEN profile = profileService.GetNewestProfile();
            if (profile != null)
            {
                do
                {
                    result = profile.Code;
                    string[] numbers = Regex.Split(result, NumberPattern);
                    int next = Convert.ToInt32(numbers[1]) + 1;
                    result = Mhs + next;
                }
                while ((profile = profileService.GetProfileByCodeId(result, -1)) != null);
            }

            return result;
        }

        /// <summary>
        /// The insert workflow profile.
        /// </summary>
        /// <param name="profile">
        /// The profile.
        /// </param>
        /// <param name="workflowProfile">
        /// The workflow profile.
        /// </param>
        /// <param name="nodeWorkflowService">
        /// The node workflow service.
        /// </param>
        /// <param name="workflowProfileService">
        /// The workflow profile service.
        /// </param>
        private void InsertWorkflowProfile(
            ProfileEN profile,
            WorkflowProfileEN workflowProfile,
            NodeWorkflowService nodeWorkflowService,
            WorkflowProfileService workflowProfileService)
        {
            workflowProfile.ProfileId = this.profileId;
            workflowProfile.WorkflowId = profile.ProfileType.WorkflowId;

            foreach (NodeWorkflowEN nodeWorkflow in
                nodeWorkflowService.GetNodeWorkflowByWorkflowId(workflowProfile.WorkflowId))
            {
                if (nodeWorkflow.Node.NodeType.Code == Constants.Nodetype.Start)
                {
                    workflowProfile.NodeId = nodeWorkflow.NodeId;
                }
            }

            workflowProfile.IsCurrent = true;
            workflowProfile.StartDate = DateTime.Now;
            workflowProfile.RW = true;
            workflowProfile.Role = MainProcess;
            if (this.userId != -1)
            {
                workflowProfile.MainUserId = this.userId;
            }

            workflowProfile.MainDepartmentId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentDepartmentId]);

            workflowProfileService.Insert(workflowProfile);
        }

        /// <summary>
        ///     The load form.
        /// </summary>
        private void LoadForm()
        {
            this.BindProfileType();
            this.BindLevel();
            ////this.BindStorages();

            if (this.Session[Constants.SessionKey.SelectedProfileType] != null)
            {
                int id = Convert.ToInt32(this.Session[Constants.SessionKey.SelectedProfileType]);
                this.Session[Constants.SessionKey.SelectedProfileType] = null;

                for (int i = 0; i < this.ddlProfileType.Items.Count; i++)
                {
                    if (this.ddlProfileType.Items[i].Value == id.ToString())
                    {
                        this.lblProfileType.Text = PublicFuncs.HtmlDecode(this.ddlProfileType.Items[i].Text);
                        this.ddlProfileType.SelectedIndex = i;
                        this.DdlProfileTypeSelectedIndexChanged(this.ddlProfileType, null);
                        break;
                    }
                }
            }

            if (this.ViewState[Constants.SessionKey.ProfileId] != null)
            {
                this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

                ////this.ViewState[Constants.SessionKey.ProfileId] = null;
            }

            this.lblNotFile.Text = string.Empty;
            if (this.profileId == -1)
            {
                ProfileStatusService profileStatusService = new ProfileStatusService();
                ProfileStatusEN profileStatus = null;
                profileStatus = profileStatusService.GetProfileStatusByCode(Constants.ProfileStatus.TIEPNHAN);
                if (profileStatus != null)
                {
                    this.txtProfileStatus.Text = profileStatus.Name; //// StartText;
                    this.ViewState[ProfileStatusViewStateKey] = profileStatus.Code;
                }

                this.imgDelete.Visible = false;
                this.txtCode.Text = this.GenerateCode();
                this.txtReceivingDate.Text = DateTime.Now.ToString(Constants.DateTimeDisplay);
                this.EnableControls(false);

                this.lbtChuyenxuly.Enabled = false;
                ////Task VONE_Maintain_24 add begin by longlc
                this.btnChuyenXuLy.Enabled = false;
                ////Task VONE_Maintain_24 add end by longlc
                this.lbtTailieu.Enabled = false;

                ////Task VONE_Maintain_24 add begin by longlc
                this.btnChuyenXuLy.Enabled = false;
                this.btnInPhieuTiepNhan.Visible = false;
                this.btnInPhieuBanGiao.Visible = false;
                ////Task VONE_Maintain_24 add end by longlc
            }
            else
            {
                UserService userService = new UserService();
                var lstUsers = userService.GetUsersByProfileId(this.profileId);
                var currentUserId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);

                if (lstUsers.Count(k => k.UserId == currentUserId) <= 0)
                {
                    ExceptionHandler.Instance.HandleUiException(new Exception(NotAccess));
                }

                ////this.EnableControls(true);
                this.lblHeader.Text = Resource.GiaiquyetthutuchanhchinhEdit_LoadForm_UpdateProfile;

                ProfileService profileService = new ProfileService();
                ProfileEN profile = new ProfileEN();
                ////ProfileStatusService profileStatusService = new ProfileStatusService();
                profile = profileService.GetProfileById(this.profileId);

                if (profile.ProfileStatus.Code == Constants.ProfileStatus.TIEPNHAN)
                {
                    this.ddlProfileType.Enabled = true;
                    if (profile.Attachments != string.Empty)
                    {
                        this.imgDelete.Visible = true;
                    }

                    this.EnableControls(true);

                    this.btnInPhieuTiepNhan.Visible = true;
                }
                else
                {
                    this.imgDelete.Visible = false;
                    this.ddlProfileType.Enabled = false;
                    this.btnProfileTypeSelect.Enabled = false;
                    this.txtProfileTypeCode.Enabled = false;
                    this.EnableControls(true);

                    this.btnInPhieuTiepNhan.Visible = false;
                }

                WorkflowProfileService workflowProfileService = new WorkflowProfileService();
                WorkflowProfileEN workflowProfile = workflowProfileService.GetWorkflowProfileByCurrent_Profile(
                    true, profile.ProfileId);
                if (workflowProfile != null)
                {
                    if (this.userId == workflowProfile.MainUserId)
                    {
                        if (this.Session[Constants.SessionKey.UpdateStatusProfileKey] != null)
                        {
                            ////Task VONE_Maintain_21 delete begin by longlc
                            ////if (profile.ProfileStatus.Code == Constants.ProfileStatus.CHOBOSUNG)
                            ////{
                            ////    profile.ProfileStatusId =
                            ////        profileStatusService.GetProfileStatusByCode(Constants.ProfileStatus.DANGBOSUNG)
                            ////                            .ProfileStatusId;
                            ////}

                            ////if (profile.ProfileStatus.Code == Constants.ProfileStatus.CHOTIEPNHAN)
                            ////{
                            ////    profile.ProfileStatusId =
                            ////        profileStatusService.GetProfileStatusByCode(Constants.ProfileStatus.DANGTIEPNHAN)
                            ////                            .ProfileStatusId;
                            ////}

                            ////if (profile.ProfileStatus.Code == Constants.ProfileStatus.CHOPHANCONG)
                            ////{
                            ////    profile.ProfileStatusId =
                            ////        profileStatusService.GetProfileStatusByCode(Constants.ProfileStatus.DANGPHANCONG)
                            ////                            .ProfileStatusId;
                            ////}

                            ////if (profile.ProfileStatus.Code == Constants.ProfileStatus.CHOTHULY)
                            ////{
                            ////    profile.ProfileStatusId =
                            ////        profileStatusService.GetProfileStatusByCode(Constants.ProfileStatus.DANGTHULY)
                            ////                            .ProfileStatusId;
                            ////}
                            ////Task VONE_Maintain_21 delete end by longlc

                            ////update status
                            this.ViewState[ProfileStatusViewStateKey] = profile.ProfileStatus.Code;
                            ////Task VONE_Maintain_51 add begin by longlc
                            profile.IsOpen = true;
                            ////Task VONE_Maintain_51 add end by longlc
                            profileService.Update(profile);

                            this.lbtChuyenxuly.Enabled = true;
                            this.btnChuyenXuLy.Enabled = true;
                            
                            this.Session[Constants.SessionKey.UpdateStatusProfileKey] = null;
                        }
                    }
                }

                ////if ket thuc
                if (profile.ProfileStatus.Code == Constants.ProfileStatus.KETTHUC)
                {
                    this.lbtChuyenxuly.Enabled = false;
                    ////Task VONE_Maintain_24 add begin by longlc
                    this.btnChuyenXuLy.Enabled = false;
                    ////Task VONE_Maintain_24 add end by longlc
                    this.DisableAll();
                }

                if (profile.ProfileStatus.Code != Constants.ProfileStatus.TIEPNHAN)
                {
                    this.DisableAll();
                }

                ////not main user
                if (workflowProfile != null)
                {
                    if (this.userId != workflowProfile.MainUserId)
                    {
                        this.lbtChuyenxuly.Enabled = false;
                        ////Task VONE_Maintain_24 add begin by longlc
                        this.btnChuyenXuLy.Enabled = false;
                        ////Task VONE_Maintain_24 add end by longlc
                    }
                }

                this.SetDataOnForm(profile);

                ////Task VONE_Maintain_24 add begin by longlc
                ////if (workflowProfile != null)
                ////{
                ////    NodeWorkflowService nodeWorkflowService = new NodeWorkflowService();
                ////    var lst = nodeWorkflowService.GetNodeWorkflowByWorkflow_Node(workflowProfile.WorkflowId,
                ////                                                       workflowProfile.NodeId);
                ////    if (lst.Count > 0)
                ////    {
                ////        if (lst[0].PrintReceipt)
                ////        {
                ////            this.btnInPhieuTiepNhan.Visible = true;
                ////        }
                ////        else
                ////        {
                ////            this.btnInPhieuTiepNhan.Visible = false;
                ////        }

                ////        if (lst[0].PrintVotehandover)
                ////        {
                ////            this.btnInPhieuBanGiao.Visible = true;
                ////        }
                ////        else
                ////        {
                ////            this.btnInPhieuBanGiao.Visible = false;
                ////        }
                ////    }
                ////}
                ////Task VONE_Maintain_24 add end by longlc
            }
        }

        /// <summary>
        /// The new profile action.
        /// </summary>
        /// <param name="profile">
        /// The profile.
        /// </param>
        /// <param name="profileService">
        /// The profile service.
        /// </param>
        /// <param name="profileCompositionProfile">
        /// The profile composition profile.
        /// </param>
        /// <param name="profileCompositionProfileListService">
        /// The profile composition profile list service.
        /// </param>
        /// <param name="workflowProfile">
        /// The workflow profile.
        /// </param>
        /// <param name="nodeWorkflowService">
        /// The node workflow service.
        /// </param>
        /// <param name="workflowProfileService">
        /// The workflow profile service.
        /// </param>
        private void NewProfileAction(
            ProfileEN profile,
            ProfileService profileService,
            ProfileCompositionProfileListEN profileCompositionProfile,
            ProfileCompositionProfileListService profileCompositionProfileListService,
            WorkflowProfileEN workflowProfile,
            NodeWorkflowService nodeWorkflowService,
            WorkflowProfileService workflowProfileService)
        {
            this.ViewState[Constants.SessionKey.ProfileId] = profileService.Insert(profile);

            this.profileId = Convert.ToInt32(this.ViewState[Constants.SessionKey.ProfileId]);

            this.ddlProfileType.Enabled = false;
            this.btnProfileTypeSelect.Enabled = false;
            this.txtProfileTypeCode.Enabled = false;

            if (profile.Attachments != string.Empty)
            {
                string path = Path.Combine(this.Server.MapPath(RootPath), profile.Attachments);
                string fileName = Path.GetFileName(path);
                if (fileName != null)
                {
                    this.lblDon.Text = this.GetFileName(fileName);
                }
            }

            ////Task VONE_Maintain_18 add begin by longlc
            if (profile.AttachmentsOriginal != string.Empty)
            {
                var lst = new List<string>();
                var files = profile.AttachmentsOriginal.Split(';');
                for (int i = 0; i < files.Length - 1; i++)
                {
                    string path = Path.Combine(this.Server.MapPath(RootPath), files[i]);
                    string fileName = Path.GetFileName(path);
                    if (fileName != null)
                    {
                        lst.Add(this.GetFileName(fileName));
                    }
                }

                this.rptHoSoGoc.DataSource = lst;
                this.rptHoSoGoc.DataBind();
            }
            ////Task VONE_Maintain_18 add end by longlc

            foreach (ListItem listItem in this.lstComposition.Items)
            {
                if (listItem.Selected)
                {
                    profileCompositionProfile.CompositionProfileListId = Convert.ToInt32(listItem.Value);
                    profileCompositionProfile.ProfileId = this.profileId;
                    profileCompositionProfileListService.Insert(profileCompositionProfile);
                }
            }

            workflowProfile.ProfileId = this.profileId;
            workflowProfile.WorkflowId = profile.ProfileType.WorkflowId;

            foreach (NodeWorkflowEN nodeWorkflow in
                nodeWorkflowService.GetNodeWorkflowByWorkflowId(workflowProfile.WorkflowId))
            {
                if (nodeWorkflow.Node.NodeType.Code == Constants.Nodetype.Start)
                {
                    workflowProfile.NodeId = nodeWorkflow.NodeId;
                }
            }

            workflowProfile.IsCurrent = true;
            workflowProfile.StartDate = DateTime.Now;
            workflowProfile.RW = true;
            workflowProfile.Role = MainProcess;
            if (this.userId != -1)
            {
                workflowProfile.MainUserId = this.userId;
            }

            workflowProfile.MainDepartmentId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentDepartmentId]);

            workflowProfileService.Insert(workflowProfile);

            this.lblMessage.ForeColor = Color.Blue;
            this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_BtnGhilaiClick_NewProfileSuccess;

            this.EnableControls(true);
        }

        /// <summary>
        /// Show Poupup ProfileType
        /// </summary>
        /// <param name="code">The code.</param>
        private void ShowPoupupProfileType(string code)
        {
            string script = ShowNewPageSeven + @"'" + code + @"','" + SelectProfileTypeText + Quots + Close;
            ScriptManager.RegisterStartupScript(this, this.GetType(), ProfileTypeKey, script, true);
        }

        /// <summary>
        /// The set data on form.
        /// </summary>
        /// <param name="profile">
        /// The profile.
        /// </param>
        private void SetDataOnForm(ProfileEN profile)
        {
            this.ddlProfileType.SelectedValue = profile.ProfileType.ProfileTypeId.ToString(CultureInfo.CurrentCulture);
            this.lblProfileType.Text = PublicFuncs.HtmlDecode(profile.ProfileType.Name.ToString(CultureInfo.CurrentCulture));
            this.txtProfileStatus.Text = profile.ProfileStatus.Name;
            this.ViewState[ProfileStatusViewStateKey] = profile.ProfileStatus.Code;

            ProfileTypeService profileTypeService = new ProfileTypeService();
            ProfileTypeEN profileType = new ProfileTypeEN();
            int profileTypeId = Convert.ToInt32(this.ddlProfileType.SelectedValue);
            profileType.ProfileTypeId = profileTypeId;

            this.BindRequirement(profileType);

            this.BindLegalGroup(profileType);

            this.BindComposition(profile);

            this.BindExtra(profileTypeService, profileTypeId);

            this.txtCode.Text = profile.Code;
            this.txtName.Text = profile.Name;
            this.txtSms.Text = profile.SmsGet;
            this.txtEmail.Text = profile.Email;
            if (profile.ReceivingDate != null)
            {
                this.txtReceivingDate.Text = profile.ReceivingDate.Value.ToString(Constants.DateTimeDisplay);
            }

            if (profile.AppointmentDate != null)
            {
                this.txtAppointmentDate.Text = profile.AppointmentDate.Value.ToString(Constants.DateTimeDisplay);
            }

            this.ddlLevel.SelectedValue = profile.Level.LevelId.ToString(CultureInfo.CurrentCulture);
            this.ddlObject.SelectedValue = profile.Object ? OneValue : TwoValue;
            this.txtOrgan.Text = profile.OrganName;
            this.txtAddress.Text = profile.Address;
            this.txtPhone.Text = profile.Phone;

            ////Task VONE_Maintain_18 delete begin by longlc
            ////string[] storages = new string[] { profile.StorageLocationProfileList.StorageLocationProfileListId.ToString(CultureInfo.CurrentCulture) };
            ////this.trvStorageLocation.CheckNodes(storages);
            ////this.ddlStorageLocation.SelectNode(
            ////    profile.StorageLocationProfileList.StorageLocationProfileListId.ToString(CultureInfo.CurrentCulture));
            ////this.ddlStorageLocation.InitialDropdownText = profile.StorageLocationProfileList.Name;
            ////this.ddlStorageLocation.DropdownText = profile.StorageLocationProfileList.Name;
            ////Task VONE_Maintain_18 delete end by longlc

            ////if (profile.SettlementDate != null)
            ////{
            ////    this.txtSettlementDate.Text = profile.SettlementDate.Value.ToString(Constants.DateTimeDisplay);
            ////}

            this.txtNotes.Text = profile.Notes;
            if (profile.ProfileType.ResultsImplementationList != null)
            {
                this.lblResultsImplementation.Text = profile.ProfileType.ResultsImplementationList.Name;
            }

            if (profile.Attachments != string.Empty)
            {
                ////this.imgDelete.Visible = true;
                string path = Path.Combine(this.Server.MapPath(RootPath), profile.Attachments);
                string fileName = Path.GetFileName(path);
                if (fileName != null)
                {
                    this.lblDon.Text = this.GetFileName(fileName);
                }
            }

            ////Task VONE_Maintain_18 add begin by longlc
            if (profile.AttachmentsOriginal != string.Empty)
            {
                var lst = new List<string>();
                var files = profile.AttachmentsOriginal.Split(';');
                for (int i = 0; i < files.Length - 1; i++)
                {
                    string path = Path.Combine(this.Server.MapPath(RootPath), files[i]);
                    string fileName = Path.GetFileName(path);
                    if (fileName != null)
                    {
                        lst.Add(this.GetFileName(fileName));
                    }
                }

                this.rptHoSoGoc.DataSource = lst;
                this.rptHoSoGoc.DataBind();
            }
            ////Task VONE_Maintain_18 add end by longlc
        }

        /// <summary>
        /// The update again profile composition.
        /// </summary>
        /// <param name="profile">
        /// The profile.
        /// </param>
        /// <param name="profileCompositionProfile">
        /// The profile composition profile.
        /// </param>
        /// <param name="profileCompositionProfileListService">
        /// The profile composition profile list service.
        /// </param>
        private void UpdateAgainProfileComposition(
            ProfileEN profile,
            ProfileCompositionProfileListEN profileCompositionProfile,
            ProfileCompositionProfileListService profileCompositionProfileListService)
        {
            profileCompositionProfileListService.DeleteByProfileId(profile.ProfileId);

            foreach (ListItem listItem in this.lstComposition.Items)
            {
                if (listItem.Selected)
                {
                    profileCompositionProfile.CompositionProfileListId = Convert.ToInt32(listItem.Value);
                    profileCompositionProfile.ProfileId = profile.ProfileId;
                    profileCompositionProfileListService.Insert(profileCompositionProfile);
                }
            }
        }

        /// <summary>
        /// The update profile action.
        /// </summary>
        /// <param name="profile">
        /// The profile.
        /// </param>
        /// <param name="profileService">
        /// The profile service.
        /// </param>
        /// <param name="profileCompositionProfile">
        /// The profile composition profile.
        /// </param>
        /// <param name="profileCompositionProfileListService">
        /// The profile composition profile list service.
        /// </param>
        /// <param name="workflowProfile">
        /// The workflow profile.
        /// </param>
        /// <param name="nodeWorkflowService">
        /// The node workflow service.
        /// </param>
        /// <param name="workflowProfileService">
        /// The workflow profile service.
        /// </param>
        private void UpdateProfileAction(
            ProfileEN profile,
            ProfileService profileService,
            ProfileCompositionProfileListEN profileCompositionProfile,
            ProfileCompositionProfileListService profileCompositionProfileListService,
            WorkflowProfileEN workflowProfile,
            NodeWorkflowService nodeWorkflowService,
            WorkflowProfileService workflowProfileService)
        {
            this.ViewState[Constants.SessionKey.ProfileId] = this.profileId;
            profile.ProfileId = this.profileId;
            profile.Code = profileService.GetProfileById(this.profileId).Code;
            profileService.Update(profile);

            if (profile.Attachments != string.Empty)
            {
                string path = Path.Combine(this.Server.MapPath(RootPath), profile.Attachments);
                string fileName = Path.GetFileName(path);
                if (fileName != null)
                {
                    this.lblDon.Text = this.GetFileName(fileName);
                    this.imgDelete.Visible = true;
                }
            }
            else
            {
                this.lblDon.Text = string.Empty;
                this.imgDelete.Visible = false;
            }

            this.UpdateAgainProfileComposition(profile, profileCompositionProfile, profileCompositionProfileListService);

            ////this.InsertWorkflowProfile(profile, workflowProfile, nodeWorkflowService, workflowProfileService);

            ////Task VONE_Maintain_18 add begin by longlc
            if (profile.AttachmentsOriginal != string.Empty)
            {
                var lst = new List<string>();
                var files = profile.AttachmentsOriginal.Split(';');
                for (int i = 0; i < files.Length - 1; i++)
                {
                    string path = Path.Combine(this.Server.MapPath(RootPath), files[i]);
                    string fileName = Path.GetFileName(path);
                    if (fileName != null)
                    {
                        lst.Add(this.GetFileName(fileName));
                    }
                }

                this.rptHoSoGoc.DataSource = lst;
                this.rptHoSoGoc.DataBind();
            }
            ////Task VONE_Maintain_18 add end by longlc

            this.lblMessage.ForeColor = Color.Blue;
            this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_BtnGhilaiClick_EditProfileSuccess;
        }

        /// <summary>
        /// Gets the name of the file.
        /// </summary>
        /// <param name="att">The attribute.</param>
        /// <returns>return string</returns>
        private string GetFileName(string att)
        {
            string[] segments = att.Split(SeparatorChar);
            StringBuilder fileName = new StringBuilder();
            for (int i = 1; i < segments.Length; i++)
            {
                fileName.Append(segments[i]);
                fileName.Append(SeparatorChar);
            }

            return fileName.ToString().Substring(0, fileName.ToString().Length - 1);
        }

        /// <summary>
        ///     The validate.
        /// </summary>
        /// <returns>
        ///     The <see cref="bool" />.
        /// </returns>
        private bool Validate()
        {
            if (this.ddlProfileType.SelectedIndex == 0)
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_ProfileTypeReq;
                return false;
            }

            if (string.IsNullOrEmpty(this.lblProfileType.Text))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_ProfileTypeReq;
                return false;
            }

            ////ProfileService profileService = new ProfileService();
            ////string code = this.txtCode.Text.Trim();
            ////if (profileService.GetProfileByCodeId(code, this.profileId) != null)
            ////{
            ////    this.lblMessage.ForeColor = Color.Red;
            ////    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_ExistCodeProfile;
            ////    return false;
            ////}
            if (string.IsNullOrEmpty(this.txtName.Text))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_ProfileNameReq;
                return false;
            }

            if (string.IsNullOrEmpty(this.txtReceivingDate.Text))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_ReceiveDateReq;
                return false;
            }

            if (string.IsNullOrEmpty(this.txtAppointmentDate.Text))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_TraDateReq;
                return false;
            }

            ////Task VONE_Maintain_18 delete begin by longlc
            ////if (string.IsNullOrEmpty(this.txtSettlementDate.Text))
            ////{
            ////    this.lblMessage.ForeColor = Color.Red;
            ////    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_NGQRequire;
            ////    return false;
            ////}
            ////Task VONE_Maintain_18 delete end by longlc

            DateTime dt1 = new DateTime();
            DateTime dt2 = new DateTime();

            if (DateTime.TryParseExact(
                this.txtAppointmentDate.Text.Trim(),
                Constants.DateTimeDisplay,
                CultureInfo.CurrentCulture,
                DateTimeStyles.None,
                out dt2))
            {
                dt2 = DateTime.ParseExact(
                    this.txtAppointmentDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture);
            }
            else
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_FillDataIntoProfile_HenTraNotValid;
                return false;
            }

            if (DateTime.TryParseExact(
                this.txtReceivingDate.Text.Trim(),
                Constants.DateTimeDisplay,
                CultureInfo.CurrentCulture,
                DateTimeStyles.None,
                out dt1))
            {
                dt1 = DateTime.ParseExact(
                    this.txtReceivingDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture);
            }
            else
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_FillDataIntoProfile_TiepNhanNotValid;
                return false;
            }

            ////Task VONE_Maintain_18 delete begin by longlc
            ////if (DateTime.TryParseExact(
            ////    this.txtSettlementDate.Text.Trim(),
            ////    Constants.DateTimeDisplay,
            ////    CultureInfo.CurrentCulture,
            ////    DateTimeStyles.None,
            ////    out dt3))
            ////{
            ////    dt3 = DateTime.ParseExact(
            ////        this.txtSettlementDate.Text.Trim(), Constants.DateTimeDisplay, CultureInfo.CurrentCulture);
            ////}
            ////else
            ////{
            ////    this.lblMessage.ForeColor = Color.Red;
            ////    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_FillDataIntoProfile_HenGQNotValid;
            ////    return false;
            ////}
            ////Task VONE_Maintain_18 delete end by longlc

            if (dt2 < dt1)
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_NTNhoHonNTN;
                return false;
            }

            if ((dt2 - dt1).Days > (int.Parse(this.lblResolveDays.Text) + PublicFuncs.GetHolidaysBetween(dt1, dt2)))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_ReceiAndTraDate;
                return false;
            }

            ////Task VONE_Maintain_18 delete begin by longlc
            ////if (dt3 < dt1)
            ////{
            ////    this.lblMessage.ForeColor = Color.Red;
            ////    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_NHGQNTN;
            ////    return false;
            ////}
            ////Task VONE_Maintain_18 delete end by longlc

            if (this.ViewState[ProfileStatusViewStateKey] != null
                && (string)this.ViewState[ProfileStatusViewStateKey] != Constants.ProfileStatus.TIEPNHAN)
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_NoEditStartProfileStatus;
                return false;
            }

            if (this.profileId != -1)
            {
                if (this.userId == -1)
                {
                    this.userId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);
                }

                WorkflowProfileService workflowProfileService = new WorkflowProfileService();
                WorkflowProfileEN workflowProfile =
                    workflowProfileService.GetWorkflowProfileByMainUser_Current_RW(this.userId, true, true);
                if (workflowProfile == null)
                {
                    this.lblMessage.ForeColor = Color.Red;
                    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_NoPermissionEditProfile;
                    return false;
                }
            }

            ////Task VONE_Maintain_18 delete begin by longlc
            ////ASTreeViewNode node = this.ddlStorageLocation.GetSelectedNode();
            ////if (node != null)
            ////{
            ////    StorageLocationProfileListService storageLocationProfileListService =
            ////        new StorageLocationProfileListService();
            ////    IList<StorageLocationProfileListEN> list =
            ////        storageLocationProfileListService.GetStorageLocationProfileListByParentId(
            ////            Convert.ToInt32(node.NodeValue), -1);
            ////    if (list.Count > 0)
            ////    {
            ////        this.lblMessage.ForeColor = Color.Red;
            ////        this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_StorageNotValid;
            ////        return false;
            ////    }
            ////}
            ////else
            ////{
            ////    this.lblMessage.ForeColor = Color.Red;
            ////    this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_NoSelectStorage;
            ////    return false;
            ////}
            ////Task VONE_Maintain_18 delete end by longlc

            if (this.fileAttachments.FileName.Length > (260 - 32))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_FileNameLengthMax;
                return false;
            }

            var profileTypeId = Convert.ToInt32(this.ddlProfileType.SelectedValue);
            var currentUser = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);
            var nodeService = new NodeService();
            var node = nodeService.GetNodes().FirstOrDefault(n => n.Code == Constants.Nodetype.Start);
            if (this.CheckPermission(currentUser, profileTypeId, node.NodeId))
            {
                this.lblMessage.ForeColor = Color.Red;
                this.lblMessage.Text = Resource.GiaiquyetthutuchanhchinhEdit_Validate_User_Cannot_CreateProfile;
                return false;
            }

            return true;
        }

        private bool CheckPermission(int currentUser,int profileTypeId, int nodeId)
        {
            var profileTypeService = new ProfileTypeService();
            var nodeWorkflowService = new NodeWorkflowService();
            var nodeWorkflowRollService = new NodeWorkflowRollService();
            int workflowId = profileTypeService.GetProfileTypeById(profileTypeId).WorkflowId;
            IList<NodeWorkflowEN> list = nodeWorkflowService.GetNodeWorkflowByWorkflow_Node(workflowId, nodeId);
            var lst = nodeWorkflowRollService.GetNodeWorkflowRollByNodeWorkflow_ToCc(list[0].NodeWorkflowId, true, profileTypeId);
            if (lst.Count > 0 && lst[0].NodeWfRoleDefaults.Count > 0 && lst[0].NodeWfRoleDefaults[0].UserDefaults.Count > 0)
            {
                var userId = lst[0].NodeWfRoleDefaults[0].UserDefaults[0].UserId;
                return userId != currentUser;
            }

            return false;
        }

        #endregion
    }
}